<template>
  <div :class="['data-selector', $attrs.class]" v-if="!disabled">
    <!-- 只读输入框、清除按钮和放大镜图标 -->
    <div class="custom-input-container">
      <RdmSelect
        ref="rdmSelect"
        :value="modelValueAsString"
        @input="updateModelValue"
        :display-label.sync="internalDisplayLabel"
        :valueKey="rowKey"
        :labelKey="labelField"
        :extendLabelKeys="selectExtendLabelKeys"
        :api="api"
        :disabled="disabled"
        :search-name="
          searchFields.find(function (item) {
            return item.type === 'input';
          }) &&
          searchFields.find(function (item) {
            return item.type === 'input';
          }).prop
        "
        :placeholder="placeholder"
        :multiple="multiple"
        :fixed-query-params="fixedQueryParams"
        @change="handleSelectChange"
      />
      <el-button
        class="search-button"
        @click="openDialog"
        icon="el-icon-search"
        :disabled="disabled"
      ></el-button>
    </div>
    <!-- 数据选择弹窗 -->
    <el-dialog
      append-to-body
      :visible.sync="dialogVisible"
      :title="title"
      :width="dialogWidth"
      :close-on-click-modal="false"
    >
      <!-- 查询条件 -->
      <div class="query-form mb20">
        <div class="search-fields-container">
          <!-- 查询字段 -->
          <div
            v-for="(item, index) in searchFields"
            :key="index"
            class="search-field-item"
          >
            <div class="field-label">{{ item.label }}：</div>
            <div class="field-input">
              <el-input
                v-if="item.type === 'input'"
                v-model="queryParams[item.prop]"
                :placeholder="'请输入' + item.label"
                clearable
                @keyup.enter.native="handleQuery"
              />
              <el-select
                v-else-if="item.type === 'select'"
                v-model="queryParams[item.prop]"
                :placeholder="'请选择' + item.label"
                clearable
              >
                <el-option
                  v-for="dict in item.options"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
              <el-date-picker
                v-else-if="item.type === 'date'"
                v-model="queryParams[item.prop]"
                :placeholder="'请选择' + item.label"
                clearable
                type="date"
                value-format="yyyy-MM-dd"
              />
              <el-date-picker
                v-else-if="item.type === 'year'"
                v-model="queryParams[item.prop]"
                :placeholder="'请选择' + item.label"
                clearable
                type="year"
                value-format="yyyy"
                format="yyyy"
              />
              <!-- 支持自定义组件类型 -->
              <component
                v-else-if="item.type === 'browser' && item.component"
                :is="item.component"
                v-model="queryParams[item.prop]"
                :query-params="queryParams"
                @search="handleQuery"
                @reset="resetQuery"
                v-bind="item.props || {}"
              />
            </div>
          </div>
        </div>

        <!-- 搜索和重置按钮单独一行靠右 -->
        <div class="search-buttons-row">
          <div style="float: right">
            <el-button type="primary" @click="handleQuery" icon="el-icon-search"
              >搜索</el-button
            >
            <el-button @click="resetQuery" icon="el-icon-refresh"
              >重置</el-button
            >
          </div>
        </div>
      </div>
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        :row-key="rowKey"
        default-expand-all
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        :height="400"
        border
        ref="tableRef"
      >
        <el-table-column
          v-if="multiple"
          :reserve-selection="true"
          type="selection"
          width="55"
          align="center"
        />
        <el-table-column v-else type="selection" width="auto" align="center">
          <template slot-scope="scope">
            <el-radio
              v-model="selectedRowKey"
              :label="scope.row[rowKey]"
              @change="handleRadioChange(scope.row)"
            >
              <span></span>
            </el-radio>
          </template>
        </el-table-column>
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="60" align="center">
          <template slot-scope="scope">
            <span>{{
              queryParams.pageSize * (queryParams.pageNum - 1) +
              scope.$index +
              1
            }}</span>
          </template>
        </el-table-column>
        <!-- 数据列 -->
        <el-table-column
          v-for="column in columns"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :formatter="column.formatter"
          align=""
          show-overflow-tooltip
        />
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>

      <!-- 弹窗底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelection">确 定</el-button>
      </span>
    </el-dialog>
  </div>
  <div v-else>{{ displayValue }}</div>
</template>

<script>
import RdmSelect from "@/components/SysSelect/index.vue";

export default {
  name: "SysBrowser",
  components: {
    RdmSelect,
  },
  props: {
    // 标题
    title: {
      type: String,
      default: "数据选择",
    },
    // 组件值（单选为主键值，多选为主键逗号拼接）
    value: {
      type: [String, Number, Array, Object],
      default: () => "",
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 表格列配置
    columns: {
      type: Array,
      required: true,
    },
    selectExtendLabelKeys: {
      type: Array,
      default: () => [],
    },
    // 查询字段配置
    searchFields: {
      type: Array,
      default: () => [],
    },
    // 数据源API（必填，支持pig-ui/api中的方法）
    api: {
      type: Function,
      required: true,
    },
    // 主键字段
    rowKey: {
      type: String,
      default: "id",
    },
    // 显示值的字段
    labelField: {
      type: String,
      default: "",
    },
    // 输入框占位符
    placeholder: {
      type: String,
      default: "点击选择数据",
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 返回值字段，默认为主键字段
    valueKey: {
      type: String,
      default: "",
    },
    // 对话框宽度
    dialogWidth: {
      type: String,
      default: "800px",
    },
    // 直接指定显示标签
    displayLabel: {
      type: String,
      default: "",
    },
    fixedQueryParams: {
      default: () => ({}),
    },
    browserType: {
      type: String,
      default: "",
    },
    queryDistrictId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      tableData: [],
      total: 0,
      selectedRows: [],
      selectedRowKey: "",

      internalDisplayLabel: this.displayLabel || "",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ...Object.fromEntries(
          this.searchFields.map((field) => [field.prop, ""])
        ),
        ...this.fixedQueryParams,
      },
    };
  },
  computed: {
    // 获取返回值的字段名
    getValueKey() {
      return this.valueKey || this.rowKey;
    },
    // 获取显示的字段名
    getLabelField() {
      if (this.labelField) {
        return this.labelField;
      }
      // 如果未设置labelField且columns有值，则使用第一个字段
      if (this.columns && this.columns.length > 0) {
        // 忽略序号列（通常是第一列）
        const firstColumn = this.columns.find(
          (col) => col.prop && col.prop !== "index" && col.type !== "index"
        );
        if (firstColumn && firstColumn.prop) {
          return firstColumn.prop;
        }
      }
      // 默认返回主键字段名
      return this.rowKey;
    },
    // 计算属性 - 将 value 转换为字符串形式供 RdmSelect 使用
    modelValueAsString() {
      if (typeof this.value === "string") {
        return this.value;
      } else if (Array.isArray(this.value)) {
        return this.value.join(",");
      } else if (typeof this.value === "number") {
        return String(this.value);
      }
      return "";
    },
    // 计算属性 - 显示的值
    displayValue() {
      // 如果提供了displayLabel，优先使用它
      if (this.displayLabel) {
        return this.displayLabel;
      }

      // 如果没有提供 displayLabel，则按原来的逻辑处理
      if (this.multiple) {
        if (this.value) {
          const values = this.parseCommaSeparatedValue(this.value);
          if (values.length === 0) return "";

          // 直接返回值，不通过tableData查找
          return values.join(", ");
        }
        return "";
      } else {
        if (this.value && typeof this.value !== "object") {
          // 直接返回值，不通过tableData查找
          return String(this.value);
        }
        return "";
      }
    },
  },
  watch: {
    selectedRowKey(newVal) {
      if (newVal) {
        const row = this.tableData.find((item) => item[this.rowKey] === newVal);
        if (row) {
          this.selectedRows = [row];
        }
      } else {
        this.selectedRows = [];
      }
    },
    value(newVal) {
      if (!newVal) {
        // 当value为空值(空字符串、null或undefined)时，同时清空所有相关状态
        this.$emit("update:displayLabel", "");
        this.selectedRows = [];
        this.selectedRowKey = "";

        // 如果表格引用存在，清空表格的选择
        if (this.$refs.tableRef) {
          this.$refs.tableRef.clearSelection();
        }
      }
    },
    internalDisplayLabel(newVal) {
      if (newVal !== this.displayLabel) {
        this.$emit("update:displayLabel", newVal);
      }
    },
    displayLabel(newVal) {
      if (newVal !== this.internalDisplayLabel) {
        this.internalDisplayLabel = newVal;
      }
    },
  },
  methods: {
    // 分解逗号分隔的字符串为数组
    parseCommaSeparatedValue(value) {
      if (!value) return [];
      if (typeof value === "string") {
        return value.split(",").filter(Boolean);
      }
      return Array.isArray(value) ? value : [value];
    },

    // 更新 value
    updateModelValue(value) {
      if (typeof this.value === "number" && !isNaN(Number(value))) {
        // 如果原始值是数字类型，保持数字类型
        this.$emit("input", Number(value));
      } else {
        // 否则使用字符串类型
        this.$emit("input", value);
      }
    },

    // 打开选择器
    openDialog() {
      this.dialogVisible = true;
      this.searchFields.forEach((field) =>
        this.$set(this.queryParams, field.prop, "")
      );
      this.getList();
    },

    // 设置选中的行
    setSelectedRows() {
      this.$nextTick(() => {
        if (this.multiple) {
          // 清除当前选中状态
          const selectedIds = [];

          if (
            this.value &&
            typeof this.value === "string" &&
            this.value.includes(",")
          ) {
            // 逗号分隔的字符串
            selectedIds.push(...this.value.split(",").filter(Boolean));
          } else if (Array.isArray(this.value)) {
            // 数组情况
            selectedIds.push(...this.value);
          } else if (this.value) {
            // 单值情况
            selectedIds.push(this.value);
          }

          // 设置选中状态
          if (selectedIds.length > 0) {
            this.tableData.forEach((row) => {
              const rowValue = String(row[this.getValueKey]);
              if (selectedIds.some((id) => String(id) === rowValue)) {
                this.$refs.tableRef &&
                  this.$refs.tableRef.toggleRowSelection(row, true);
              }
            });
          }
        } else {
          if (this.value) {
            // 纯值模式 - 将任意类型转换为字符串，以保证兼容性
            this.selectedRowKey = String(this.value);
          }
        }
      });
    },

    // 过滤查询参数，移除空字符串和null值
    filterQueryParams(params) {
      const filteredParams = {};
      for (const [key, value] of Object.entries(params)) {
        if (value !== "" && value !== null && value !== undefined) {
          filteredParams[key] = value;
        }
      }
      return filteredParams;
    },

    // 获取列表数据
    getList() {
      this.loading = true;
      // 过滤查询参数，移除空字符串和null值
      const filteredParams = this.filterQueryParams(this.queryParams);
      // 使用提供的API函数作为数据源
      this.api({ ...filteredParams, DID: this.queryDistrictId })
        .then((res) => {
          if (res && res.data) {
            // 兼容不同的后端返回格式
            if (res.data.list) {
              // 常见的分页格式: { list: [], total: number }
              this.tableData = res.data.list || [];
              this.total = res.data.total || 0;
            } else if (Array.isArray(res.data)) {
              // 直接返回数组形式
              this.tableData = res.data;
              this.total = res.data.length;
            } else if (res.data.records) {
              // 兼容旧格式: { records: [], total: number }
              this.tableData = res.data.records || [];
              this.total = res.data.total || 0;
            } else if (res.data.rows) {
              // 另一种常见的分页格式: { rows: [], total: number }
              this.tableData = res.data.rows || [];
              this.total = res.data.total || 0;
            } else {
              this.tableData = [];
              this.total = 0;
              console.warn("无法解析的数据格式:", res);
            }
          } else {
            this.tableData = [];
            this.total = 0;
          }

          // 设置选中行状态
          this.setSelectedRows();
          this.loading = false;
        })
        .catch((error) => {
          console.error("获取数据失败:", error);
          this.tableData = [];
          this.total = 0;
          this.loading = false;
          this.$message.error("获取数据失败");
        });
    },

    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置查询
    resetQuery() {
      this.searchFields.forEach((field) =>
        this.$set(this.queryParams, field.prop, "")
      );
      this.handleQuery();
    },

    // 处理选择变化 (多选)
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    // 处理行点击事件
    handleRowClick(row) {
      if (this.multiple) {
        // 多选模式：切换当前行的选中状态
        this.$refs.tableRef && this.$refs.tableRef.toggleRowSelection(row);
      } else {
        // 单选模式：设置单选按钮的值并自动确认
        this.selectedRowKey = row[this.rowKey];
        this.selectedRows = [row];
        this.confirmSelection();
      }
    },

    // 单选变化
    handleRadioChange(row) {
      this.selectedRows = [row];
      // 单选模式下自动触发确认
      this.confirmSelection();
    },

    // 确认选择
    confirmSelection() {
      if (this.multiple) {
        if (this.selectedRows.length === 0) {
          this.$message.warning("请至少选择一条数据");
          return;
        }

        // 先通知RdmSelect缓存数据，避免后续API调用
        this.$refs.rdmSelect.cacheSelectedData(this.selectedRows);

        // 多选模式下返回逗号分隔的字符串
        const values = this.selectedRows.map((row) => row[this.getValueKey]);
        const joinedValues = values.join(",");
        this.$emit("input", joinedValues);
        this.$emit("change", this.selectedRows);

        // 同步更新displayLabel
        const displayNames = this.selectedRows.map(
          (row) => row[this.getLabelField]
        );
        const displayText = displayNames.join(",");
        this.internalDisplayLabel = displayText;
        this.$emit("update:displayLabel", displayText);
      } else {
        if (!this.selectedRows.length) {
          this.$message.warning("请选择一条数据");
          return;
        }

        // 先通知RdmSelect缓存数据，避免后续API调用
        this.$refs.rdmSelect.cacheSelectedData(this.selectedRows);

        // 单选模式返回主键值
        const value = this.selectedRows[0][this.getValueKey];
        this.$emit("input", value);
        this.$emit("change", this.selectedRows[0]);

        // 同步更新displayLabel
        const displayText = this.selectedRows[0][this.getLabelField];
        this.internalDisplayLabel = displayText;
        this.$emit("update:displayLabel", displayText);
      }
      this.dialogVisible = false;
    },

    // 处理RdmSelect的change事件
    handleSelectChange(data) {
      this.$emit("change", data);
    },

    // 清除选择
    clearSelection() {
      this.$emit("input", "");
      this.$emit("change", null);
      // 同步清除displayLabel
      this.internalDisplayLabel = "";
      this.$emit("update:displayLabel", "");
      this.selectedRows = [];
      this.selectedRowKey = "";
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
  },
};
</script>

<style scoped>
.data-selector {
  width: 100%;
}

.custom-input-container {
  display: flex;
  align-items: center;
  gap: 1px;
}

.custom-input-container > :first-child {
  flex: 1;
}

.search-button {
  height: auto;
  flex-shrink: 0;
  border-radius: 4px;
}

.input-with-search .el-input__wrapper {
  cursor: pointer;
}

.input-clear-icon {
  color: #c0c4cc;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s;
}

.input-clear-icon:hover {
  color: #909399;
}

.query-form {
  margin-bottom: 20px;
  margin-top: -20px;
  padding-top: 0;
}

.search-fields-container {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 0;
}

.search-field-item {
  display: flex;
  align-items: center;
  margin-right: 40px;
  margin-bottom: 10px;
  width: 43%;
}

.field-label {
  white-space: nowrap;
  font-size: 14px;
  color: #606266;
  text-align: left;
}

.field-input {
  flex: 1;
  min-width: 180px;
}

.search-buttons-row {
  margin-top: -10 px;
  margin-bottom: -10px;
}

.mb20 {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

::v-deep .el-radio {
  margin-right: 0;
}

::v-deep .el-radio__label {
  display: none;
}
</style>
